<template>
  <div class="nav-page">
    <div class="container-card">
      <section class="card">
        <header class="card-header">
          <div class="title">{{ paper?.name || '开始考试' }}</div>
          <div class="ops">
            <el-button size="small" @click="goBack">返回</el-button>
          </div>
        </header>
        <div class="card-body">
          <div class="paper-meta" v-if="paper">
            <span>时长：{{ paper.durationMinutes }} 分钟</span>
            <span>总分：{{ paper.totalScore }}</span>
            <span>及格线：{{ paper.passScore }}</span>
          </div>

          <div v-loading="loading" class="question-list">
            <div v-for="(item, index) in questionItems" :key="item.id || index" class="question-card">
              <!-- 第一行：题型 + 题干（无正确答案、无删除按钮） -->
              <div class="question-header">
                <div class="question-info">
                  <span class="question-index">{{ index + 1 }}.</span>
                  <span class="question-stem">{{ item.question.stem }}</span>
                  <el-tag :type="typeTagType(item.question.questionType)" size="small" class="type-tag">
                    {{ typeText(item.question.questionType) }}
                  </el-tag>
                </div>
              </div>

              <!-- 第二行：选项（可点击选择） -->
              <div class="question-options" v-if="hasOptions(item)">
                <div class="opt-list" :class="isShortOptions(item.options) ? 'opt-short' : 'opt-long'">
                  <div v-for="(opt, idx) in normalizeOptions(item.options)" :key="idx" class="opt-item"
                    :class="{ selected: isSelectedOption(item, idx) }" @click="toggleOption(item, idx)">
                    <span class="opt-index">{{ indexLabel(idx) }}</span>
                    <span class="opt-text">{{ optionText(opt) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="questionItems.length === 0 && !loading" class="empty-state">
              暂无题目数据
            </div>
          </div>

          <!-- 底部提交按钮（居中，固定在卡片底部） -->
          <div class="submit-bar">
            <el-button type="primary" size="large" @click="submitExam">提交试卷</el-button>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getPaperDetail, submitAnswers } from '@/api/exam/exam'

const route = useRoute()
const router = useRouter()
const paperId = Number(route.params.paperId)
// 可选 attemptId（从 query 获取），便于后续提交答案
const attemptId = route.query.attemptId ? String(route.query.attemptId) : undefined

const paper = ref<any | null>(null)
const loading = ref(false)
const questionItems = ref<any[]>([])
const startTs = Date.now()

// 作答状态：questionId -> 选中的 optionKey 列表（多选支持多个）
const answers = ref<Record<number, string[]>>({})

function typeText(t?: number) {
  return t === 1 ? '单选' : t === 2 ? '多选' : t === 3 ? '判断' : t === 4 ? '填空' : '-'
}
function typeTagType(t?: number) {
  return t === 1 ? 'success' : t === 2 ? 'warning' : t === 3 ? 'info' : t === 4 ? 'primary' : 'default'
}

async function loadDetail() {
  loading.value = true
  try {
    const paperRes = await getPaperDetail(paperId)
    if (paperRes.data && paperRes.data.code === 0) {
      paper.value = paperRes.data.data.paper
      questionItems.value = paperRes.data.data.items
    } else {
      throw new Error('接口返回数据格式错误')
    }
    // 初始化答案结构
    questionItems.value.forEach((it: any) => {
      const qid = it.question.id
      if (qid != null && answers.value[qid] == null) answers.value[qid] = []
    })
  } catch (e) {
    ElMessage.error('加载试卷详情失败')
  } finally {
    loading.value = false
  }
}

function goBack() {
  router.back()
}

onMounted(loadDetail)

// —— 选项显示相关 ——
function optionText(o: any): string {
  if (o == null) return ''
  if (typeof o === 'string') return o
  return o.content ?? o.text ?? o.label ?? o.value ?? (typeof o === 'object' ? JSON.stringify(o) : String(o))
}
function normalizeOptions(opts: any): any[] { return Array.isArray(opts) ? opts : [] }
function isShortOptions(opts: any): boolean {
  const arr = normalizeOptions(opts)
  if (arr.length !== 4) return false
  const threshold = 12
  return arr.every((o) => optionText(o).length <= threshold)
}
function indexLabel(idx: number): string { const map = ['A', 'B', 'C', 'D', 'E', 'F']; return map[idx] ?? String(idx + 1) }

// 判断是否有可选项（单选/多选/判断显示选项，填空暂不显示）
function hasOptions(item: any): boolean {
  const t = item?.question?.questionType
  if (t === 1 || t === 2 || t === 3) {
    const opts = item?.options
    return Array.isArray(opts) && opts.length > 0
  }
  return false
}

// —— 选项选择逻辑 ——
function isSelectedOption(item: any, optionIndex: number): boolean {
  const qid = item?.question?.id
  if (qid == null) return false
  const opt = item.options?.[optionIndex]
  const key = opt?.optionKey
  if (!key) return false
  return (answers.value[qid] || []).includes(key)
}

function toggleOption(item: any, optionIndex: number) {
  const qtype = item?.question?.questionType
  const qid = item?.question?.id
  const opt = item.options?.[optionIndex]
  const key = opt?.optionKey
  if (qid == null || !key) return

  const current = answers.value[qid] || []
  if (qtype === 2) {
    // 多选：切换包含状态
    if (current.includes(key)) {
      answers.value[qid] = current.filter((k) => k !== key)
    } else {
      answers.value[qid] = [...current, key]
    }
  } else {
    // 单选/判断：覆盖为单个
    answers.value[qid] = [key]
  }
}

// 将判断题选项尝试映射为布尔值（尽量兼容常见文案/键值）
function toBooleanAnswer(item: any, selectedKey?: string): boolean | undefined {
  if (!item || !selectedKey) return undefined
  const opt = (item.options || []).find((o: any) => o?.optionKey === selectedKey)
  const text = opt ? optionText(opt) : ''
  const keyUpper = String(selectedKey || '').toUpperCase()
  const truthy = ['T', 'TRUE', 'Y', 'YES', '1', 'A']
  const falsy = ['F', 'FALSE', 'N', 'NO', '0', 'B']
  if (truthy.includes(keyUpper)) return true
  if (falsy.includes(keyUpper)) return false
  if (text.includes('正确') || text.includes('是')) return true
  if (text.includes('错误') || text.includes('否')) return false
  return undefined
}

// 提交答案（调用后端 submitAnswers，成功后跳转到考试主页）
async function submitExam() {
  const timeSpentSeconds = Math.max(0, Math.floor((Date.now() - startTs) / 1000))
  const total = questionItems.value.length
  const answeredCount = Object.values(answers.value).filter((arr) => Array.isArray(arr) && arr.length > 0).length

  if (!attemptId) {
    ElMessage.error('缺少尝试ID，请从考试列表开始考试后再提交')
    return
  }

  const payload: any = { timeSpentSeconds, answers: [] as any[] }
  for (const it of questionItems.value) {
    const qid = it?.question?.id
    const qtype = it?.question?.questionType
    if (qid == null) continue
    const selected = answers.value[qid] || []
    if (!selected.length) continue
    if (qtype === 1 || qtype === 2) {
      payload.answers.push({ questionId: qid, selectedOptionKeys: selected })
    } else if (qtype === 3) {
      const bool = toBooleanAnswer(it, selected[0])
      if (typeof bool === 'boolean') {
        payload.answers.push({ questionId: qid, booleanAnswer: bool })
      } else {
        // 兼容后端若接受选项形式
        payload.answers.push({ questionId: qid, selectedOptionKeys: [selected[0]] })
      }
    }
    // 填空题（qtype === 4）当前未在页面展示，不参与提交
  }

  try {
    const { data } = await submitAnswers(String(attemptId), payload)
    if (data && data.code === 0) {
      ElMessage.success(`提交成功：已答 ${answeredCount}/${total} 题`)
      // 跳转到在线考试主页
      router.push('/examOnline')
    } else {
      throw new Error('提交失败')
    }
  } catch (e) {
    ElMessage.error('提交试卷失败，请稍后重试')
  }
}
</script>

<style scoped>
.nav-page {
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  background: #f5f7fb;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 20px;
  padding-bottom: 20px;
}

.container-card {
  height: 95vh;
  min-width: 900px;
  max-width: 1260px;
  margin: 0 auto;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 20px;
  box-shadow: 0 10px 24px rgba(31, 45, 61, 0.06);
  padding-top: 20px;
  padding-bottom: 24px;
  padding-left: 60px;
  padding-right: 60px;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 6px 12px 6px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header .title {
  font-weight: 600;
}

.card-header .ops {
  display: flex;
  gap: 8px;
  align-items: center;
}

.card-body {
  padding-top: 12px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.paper-meta {
  display: flex;
  gap: 12px;
  color: #666;
  margin-bottom: 10px;
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
  flex: 1;
  overflow-y: auto;
}

.question-card {
  border: none;
  border-radius: 0;
  padding: 8px 0;
  background: transparent;
  box-shadow: none;
  transition: none;
}

.question-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 3px;
}

.question-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.type-tag {
  flex-shrink: 0;
}

.question-stem {
  color: #1f2937;
  font-weight: 500;
  line-height: 1.5;
}

.question-index {
  color: #374151;
  font-weight: 600;
  margin: 0 6px 0 8px;
}

.question-options {
  margin-left: 8px;
  margin-top: 1px;
}

.empty-state {
  text-align: center;
  color: #6b7280;
  padding: 40px 20px;
  font-size: 16px;
}

.opt-list {
  display: grid;
  gap: 8px;
}

.opt-short {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

.opt-long {
  grid-template-columns: 1fr;
}

.opt-item {
  border: none;
  border-radius: 8px;
  padding: 6px 8px;
  background: transparent;
  display: flex;
  gap: 8px;
  align-items: flex-start;
  transition: all 0.2s ease;
  cursor: pointer;
}

.opt-item:hover {
  background: #f9fafb;
}

.opt-item.selected {
  background: #eef2ff;
}

.opt-index {
  font-weight: 600;
  color: #4b5563;
}

.opt-text {
  color: #1f2937;
  word-break: break-word;
}

/* 底部提交按钮栏 */
.submit-bar {
  display: flex;
  justify-content: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
}

@media (max-width: 720px) {
  .container-card {
    padding-left: 16px;
    padding-right: 16px;
  }

  .opt-short {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
